export default {
    // 命名空间锁
    namespaced: true,
    state: {
    // 购物车数组
    cartList: uni.getStorageSync("cartList") || []
      
    },
    getters: {
        // 已选择商品数组
        checkedCartList(state){
            // console.log(state);
            return state.cartList.filter((item) => item.checked === true);
        },
        // 封装合计
        checkedPrice(state,getters){
            // console.log(getters,16);
            return getters.checkedCartList.reduce((price, item) => price += item.nums * item.goods_price, 0);
        },
        // 商品总数量
        checkedCount(state, getters) {
            return getters.checkedCartList.reduce((count, item) => count += item.nums, 0);
          }
    },
    mutations: {
        cartClick(state,payload){
            // console.log(payload,20);
            const index = state.cartList.findIndex(item=>payload.value.goods_id===item.goods_id)
            // console.log(index);
            if(index===-1){
                // 不存在
            state.cartList.push({...payload.value,nums:1,checked:true})
            }else{
                // 存在
                state.cartList[index].nums++
            }
            uni.setStorageSync("cartList",state.cartList);
            // console.log(state.cartList);
        },
        // 复选框
        goodsCheckChange(state,payload){
            // console.log(payload);
        state.cartList[payload.index].checked = !state.cartList[payload.index].checked
        uni.setStorageSync("cartList",state.cartList);
        },
        // 数量编辑
        goodsCountChange(state,payload){
            // console.log(payload);
            // console.log(state);
            state.cartList[payload.index].nums+=payload.unit
            uni.setStorageSync("cartList",state.cartList);
        },
        // 商品删除
        goodsRemoveChange(state,payload){
            // console.log(payload);
            state.cartList.splice(payload.index,1)
            uni.setStorageSync("cartList",state.cartList);
        },
        goodsCheckAll(state,payload){
            // console.log(payload);
            state.cartList.forEach(item=>item.checked=payload.checked)
            uni.setStorageSync("cartList",state.cartList);
            
        }
        
    },
    actions: { 

    }
}